home *** CD-ROM | disk | FTP | other *** search
/ Mac Easy 2010 May / Mac Life Ubuntu.iso / casper / filesystem.squashfs / var / lib / python-support / python2.6 / glchess / network.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2009-04-20  |  21.4 KB  |  643 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. import os
  5. import socket
  6. import errno
  7. import gettext
  8. import ggz
  9. import ui
  10. import game
  11. from defaults import *
  12. _ = gettext.gettext
  13.  
  14. class GGZServer:
  15.     
  16.     def __init__(self, name):
  17.         self.name = name
  18.  
  19.  
  20.  
  21. class GGZLine:
  22.     TYPE_BLANK = 'BLANK'
  23.     TYPE_COMMENT = 'COMMENT'
  24.     TYPE_SECTION = 'SECTION'
  25.     TYPE_FIELD = 'FIELD'
  26.     TYPE_INVALID = 'INVALID'
  27.     
  28.     def __init__(self, text):
  29.         self.text = text
  30.         self.section = None
  31.         
  32.         try:
  33.             self.decode(text)
  34.         except ValueError:
  35.             e = None
  36.             self.type = GGZLine.TYPE_INVALID
  37.             print e
  38.  
  39.  
  40.     
  41.     def decode(self, text):
  42.         content = text.strip()
  43.         if len(content) == 0:
  44.             self.type = GGZLine.TYPE_BLANK
  45.         elif content[0] == '#':
  46.             self.type = GGZLine.TYPE_COMMENT
  47.         elif content[0] == '[':
  48.             self.type = GGZLine.TYPE_SECTION
  49.             if content[-1] != ']':
  50.                 raise ValueError('Invalid section line: %s' % repr(content))
  51.             content[-1] != ']'
  52.             self.name = content[1:-1].strip()
  53.             self.value = None
  54.         else:
  55.             self.type = GGZLine.TYPE_FIELD
  56.             
  57.             try:
  58.                 (name, value) = content.split('=', 1)
  59.             except ValueError:
  60.                 raise ValueError('Invalid field line: %s' % repr(content))
  61.  
  62.             self.name = name.strip()
  63.             self.value = value.strip()
  64.  
  65.     
  66.     def setValue(self, value):
  67.         if not self.type is GGZLine.TYPE_FIELD:
  68.             raise AssertionError
  69.         self.value = value
  70.         self.text = '%s=%s\n' % (self.name, value)
  71.  
  72.  
  73.  
  74. class GGZConfig:
  75.     TYPE_NORMAL = 0
  76.     TYPE_GUEST = 1
  77.     TYPE_FIRST = 2
  78.     
  79.     def __init__(self):
  80.         
  81.         try:
  82.             f = file(GGZ_CONFIG_FILE)
  83.             lines = f.readlines()
  84.         except IOError:
  85.             e = None
  86.             print 'Failed to load GGZ config: %s' % e.message
  87.             lines = []
  88.  
  89.         self.lines = []
  90.         section = None
  91.         for text in lines:
  92.             line = GGZLine(text)
  93.             self.lines.append(line)
  94.             if line.type is GGZLine.TYPE_SECTION:
  95.                 section = line.name
  96.                 line.section = section
  97.                 continue
  98.             line.section = section
  99.         
  100.  
  101.     
  102.     def getField(self, section, name):
  103.         for line in self.lines:
  104.             if line.section != section or line.type is not GGZLine.TYPE_FIELD:
  105.                 continue
  106.             
  107.             if line.name == name:
  108.                 return line.value
  109.         
  110.         raise KeyError('No field %s in section %s' % (name, section))
  111.  
  112.     
  113.     def setField(self, section, name, value):
  114.         wasInSection = False
  115.         inSection = False
  116.         for index, line in enumerate(self.lines):
  117.             wasInSection = inSection
  118.             if line.section == section:
  119.                 inSection = True
  120.                 if line.type is GGZLine.TYPE_FIELD and line.name == name:
  121.                     line.setValue(value)
  122.                     return None
  123.                 continue
  124.             line.name == name
  125.             if wasInSection and not inSection:
  126.                 line = GGZLine('%s=%s\n' % (name, value))
  127.                 line.section = section
  128.                 self.lines.insert(index, line)
  129.                 return None
  130.         
  131.         line = GGZLine('%s=%s\n' % (name, value))
  132.         line.section = section
  133.         self.lines.append(line)
  134.  
  135.     
  136.     def removeSection(self, name):
  137.         keptLines = []
  138.         for line in self.lines:
  139.             if line.section != name:
  140.                 keptLines.append(line)
  141.                 continue
  142.         
  143.         self.lines = keptLines
  144.  
  145.     
  146.     def getServers(self):
  147.         
  148.         try:
  149.             value = self.getField('Servers', 'ProfileList')
  150.         except KeyError:
  151.             e = None
  152.             return []
  153.  
  154.         servers = []
  155.         for n in value.replace('\\ ', '\x00').split(' '):
  156.             name = n.replace('\x00', ' ')
  157.             
  158.             try:
  159.                 server = self.getServer(name)
  160.             except KeyError:
  161.                 e = None
  162.                 print e
  163.                 continue
  164.  
  165.             servers.append(server)
  166.         
  167.         return servers
  168.  
  169.     
  170.     def getServer(self, name):
  171.         server = GGZServer(name)
  172.         
  173.         try:
  174.             server.host = self.getField(name, 'Host')
  175.             server.port = int(self.getField(name, 'Port'))
  176.             server.login = self.getField(name, 'Login')
  177.             server.loginType = int(self.getField(name, 'Type'))
  178.         except (KeyError, ValueError):
  179.             raise KeyError('Missing/invalid basic configuration for server %s' % repr(server.name))
  180.  
  181.         
  182.         try:
  183.             server.password = self.getField(name, 'Password')
  184.         except KeyError:
  185.             server.password = None
  186.  
  187.         return server
  188.  
  189.     
  190.     def updateServer(self, name, username, host, port):
  191.         self.setField(name, 'Host', host)
  192.         self.setField(name, 'Port', port)
  193.         self.setField(name, 'Login', username)
  194.         self.setField(name, 'Type', GGZConfig.TYPE_GUEST)
  195.         
  196.         try:
  197.             servers = self.getField('Servers', 'ProfileList')
  198.         except KeyError:
  199.             e = None
  200.             self.setField('Servers', 'ProfileList', name.replace(' ', '\\ '))
  201.  
  202.         self.setField('Servers', 'ProfileList', servers + ' ' + name.replace(' ', '\\ '))
  203.         self.save()
  204.  
  205.     
  206.     def save(self):
  207.         lines = []
  208.         for line in self.lines:
  209.             lines.append(line.text)
  210.         
  211.         
  212.         try:
  213.             f = file(GGZ_CONFIG_FILE, 'w')
  214.             f.writelines(lines)
  215.         except IOError:
  216.             e = None
  217.             print 'Failed to save GGZ config: %s' % e.message
  218.  
  219.  
  220.  
  221.  
  222. class GGZChannel(ggz.Channel):
  223.     
  224.     def __init__(self, ui, feedback):
  225.         self.buffer = ''
  226.         self.ui = ui
  227.         self.feedback = feedback
  228.         self.socket = None
  229.         self.fd = -1
  230.  
  231.     
  232.     def logXML(self, text):
  233.         self.logWindow.addText(text, 'input')
  234.  
  235.     
  236.     def logBinary(self, data):
  237.         self.logWindow.addBinary(data, 'input')
  238.  
  239.     
  240.     def connect(self, host, port):
  241.         self.close()
  242.         self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  243.         self.fd = self.socket.fileno()
  244.         self.socket.setblocking(False)
  245.         self.ui.application.ioHandlers[self.fd] = self
  246.         self.ui.controller.watchFileDescriptor(self.fd)
  247.         
  248.         try:
  249.             self.socket.connect((host, port))
  250.         except socket.error:
  251.             e = None
  252.             if e.args[0] == errno.EINPROGRESS:
  253.                 print 'connecting...'
  254.             else:
  255.                 print e
  256.         except:
  257.             e.args[0] == errno.EINPROGRESS
  258.  
  259.         name = '%s:%d' % (host, port)
  260.         self.logWindow = self.ui.controller.addLogWindow(name, name, name)
  261.  
  262.     
  263.     def send(self, data, isBinary = False):
  264.         if isBinary:
  265.             self.logWindow.addBinary(data, 'output')
  266.         else:
  267.             self.logWindow.addText(data, 'output')
  268.         self.buffer += data
  269.         
  270.         try:
  271.             nSent = self.socket.send(self.buffer)
  272.         except socket.error:
  273.             self
  274.             self
  275.             nSent = 0
  276.         except:
  277.             self
  278.  
  279.         self.buffer = self.buffer[nSent:]
  280.  
  281.     
  282.     def close(self):
  283.         if self.socket is None:
  284.             return None
  285.         self.ui.controller.unwatchFileDescriptor(self.fd)
  286.         self.socket.close()
  287.         self.socket = None
  288.         self.fd = -1
  289.  
  290.     
  291.     def read(self):
  292.         
  293.         try:
  294.             (data, address) = self.socket.recvfrom(65535)
  295.         except socket.error:
  296.             e = None
  297.             
  298.             try:
  299.                 self.socket.close()
  300.             except socket.error:
  301.                 pass
  302.  
  303.             self.feedback.closed(e.args[0])
  304.             return False
  305.  
  306.         if len(data) == 0:
  307.             self.feedback.closed()
  308.             return False
  309.         self.feedback.registerIncomingData(data)
  310.         return True
  311.  
  312.  
  313.  
  314. class GGZConnection(ggz.ClientFeedback):
  315.     
  316.     def __init__(self, dialog):
  317.         self.dialog = dialog
  318.         self.profile = dialog.profile
  319.         self.client = ggz.Client(self)
  320.         self.commands = []
  321.         self.sending = False
  322.         self.players = { }
  323.         self.actions = []
  324.  
  325.     
  326.     def _getPlayerIcon(self, player):
  327.         
  328.         try:
  329.             return {
  330.                 'guest': 'stock_person',
  331.                 'normal': 'stock_person',
  332.                 'admin': 'stock_person',
  333.                 'bot': 'stock_notebook' }[player.type]
  334.         except KeyError:
  335.             return ''
  336.  
  337.  
  338.     
  339.     def _performAction(self, method, args):
  340.         if self.client.isBusy():
  341.             self.actions.insert(0, (method, args))
  342.         else:
  343.             method(*args)
  344.  
  345.     
  346.     def close(self):
  347.         self.client.close('')
  348.  
  349.     
  350.     def setBusy(self, isBusy):
  351.         self.dialog.controller.setBusy(isBusy)
  352.         if not isBusy and len(self.actions) > 0:
  353.             (method, args) = self.actions.pop()
  354.             method(*args)
  355.         
  356.  
  357.     
  358.     def onConnected(self):
  359.         self.dialog.controller.setSensitive(True)
  360.         self.dialog.controller.clearError()
  361.  
  362.     
  363.     def onDisconnected(self, reason):
  364.         self.dialog.controller.setError(_('Disconnected from server'), reason)
  365.         self.dialog.controller.setSensitive(False)
  366.  
  367.     
  368.     def openChannel(self, feedback):
  369.         print 'Open Channel'
  370.         self.setBusy(True)
  371.         socket = GGZChannel(self.dialog.ui, feedback)
  372.         socket.connect(self.profile.host, self.profile.port)
  373.         return socket
  374.  
  375.     
  376.     def getLogin(self):
  377.         return (self.profile.login, self.profile.password)
  378.  
  379.     
  380.     def getPassword(self, username):
  381.         self.client.setPassword(self.profile.password)
  382.  
  383.     
  384.     def onMOTD(self, motd):
  385.         self.dialog.controller.addText(motd, 'motd')
  386.  
  387.     
  388.     def roomAdded(self, room):
  389.         if room.game is None and room.game.protocol_engine == 'Chess':
  390.             pass
  391.         isChess = room.game.protocol_version == '3'
  392.         if room.game is None:
  393.             protocol = None
  394.         else:
  395.             protocol = room.game.protocol_engine
  396.         self.dialog.controller.addRoom(int(room.id), room.name, room.nPlayers, room.description, room, protocol)
  397.  
  398.     
  399.     def roomUpdated(self, room):
  400.         self.dialog.controller.updateRoom(room, room.nPlayers)
  401.  
  402.     
  403.     def roomEntered(self, room):
  404.         self.room = room
  405.         self.dialog.controller.clearPlayers()
  406.         self.dialog.controller.clearTables()
  407.         for player in self.client.players.itervalues():
  408.             self.dialog.controller.addPlayer(player, player.name, self._getPlayerIcon(player))
  409.         
  410.         for table in self.client.tables.itervalues():
  411.             self.tableAdded(table)
  412.         
  413.         self.dialog.controller.enterRoom(room)
  414.  
  415.     
  416.     def tableAdded(self, table):
  417.         self.tableUpdated(table)
  418.  
  419.     
  420.     def tableUpdated(self, table):
  421.         if table.room != self.room:
  422.             return None
  423.         description = table.description
  424.         if len(description) == 0:
  425.             description = _('No description')
  426.         
  427.         nUsed = 0
  428.         for seat in table.seats:
  429.             if seat.type == 'bot' or seat.user != '':
  430.                 nUsed += 1
  431.                 continue
  432.         
  433.         if table.room.game is not None:
  434.             pass
  435.         isChess = table.room.game.protocol_engine == 'Chess'
  436.         if isChess:
  437.             pass
  438.         canConnect = nUsed != len(table.seats)
  439.         self.dialog.controller.updateTable(table, '%s' % table.id, '%i/%i' % (nUsed, len(table.seats)), description, canConnect)
  440.         for i, seat in enumerate(table.seats):
  441.             self.dialog.controller.updateSeat(table, i, seat.type, seat.user)
  442.         
  443.  
  444.     
  445.     def tableRemoved(self, table):
  446.         if table.room == self.room:
  447.             self.dialog.controller.removeTable(table)
  448.         
  449.  
  450.     
  451.     def onJoin(self, table, isSpectator, channel):
  452.         self.dialog.controller.joinTable(table)
  453.         g = GGZChess(self.dialog.game, channel)
  454.         return g
  455.  
  456.     
  457.     def onLeave(self, reason):
  458.         print 'Leave table: %s' % reason
  459.         self.dialog.controller.joinTable(None)
  460.  
  461.     
  462.     def playerAdded(self, player):
  463.         self.dialog.controller.addPlayer(player, player.name, self._getPlayerIcon(player))
  464.  
  465.     
  466.     def playerRemoved(self, player):
  467.         self.dialog.controller.removePlayer(player)
  468.  
  469.     
  470.     def onChat(self, chatType, sender, text):
  471.         self.dialog.controller.addText('\n%s: %s' % (sender, text), 'chat')
  472.  
  473.  
  474.  
  475. class GGZChess:
  476.     '''
  477.     '''
  478.     
  479.     def __init__(self, game, channel):
  480.         self.game = game
  481.         self.channel = channel
  482.         self.protocol = ggz.Chess(self)
  483.  
  484.     
  485.     def registerIncomingData(self, data):
  486.         for o in data:
  487.             self.protocol.decode(o)
  488.         
  489.  
  490.     
  491.     def onSeat(self, seatNum, version):
  492.         self.seatNum = seatNum
  493.         print ('onSeat', seatNum, version)
  494.  
  495.     
  496.     def seatIsFull(self, seatType):
  497.         if not seatType == self.protocol.GGZ_SEAT_PLAYER:
  498.             pass
  499.         return seatType == self.protocol.GGZ_SEAT_BOT
  500.  
  501.     
  502.     def onPlayers(self, whiteType, whiteName, blackType, blackName):
  503.         print ('onPlayers', whiteType, whiteName, blackType, blackName)
  504.         self.whiteName = whiteName
  505.         self.blackName = blackName
  506.  
  507.     
  508.     def onClockRequest(self):
  509.         print ('onTimeRequest',)
  510.         self.channel.send(self.protocol.sendClock(self.protocol.CLOCK_NONE, 0), True)
  511.  
  512.     
  513.     def onClock(self, mode, seconds):
  514.         print ('onClock', mode, seconds)
  515.  
  516.     
  517.     def onStart(self):
  518.         print ('onStart',)
  519.         if self.seatNum == 0:
  520.             name = self.blackName
  521.         else:
  522.             name = self.whiteName
  523.         self.remotePlayer = game.ChessPlayer(name)
  524.         self.remotePlayer.onPlayerMoved = self.onPlayerMoved
  525.         p = self.game.addHumanPlayer('Human')
  526.         if self.seatNum == 0:
  527.             self.game.setWhite(p)
  528.             self.game.setBlack(self.remotePlayer)
  529.         else:
  530.             self.game.setWhite(self.remotePlayer)
  531.             self.game.setBlack(p)
  532.         self.game.start()
  533.  
  534.     
  535.     def onPlayerMoved(self, player, move):
  536.         if player is not self.remotePlayer:
  537.             self.channel.send(self.protocol.sendMove(move.canMove.upper()), True)
  538.         
  539.  
  540.     
  541.     def onMove(self, move):
  542.         print ('onMove', move)
  543.         self.remotePlayer.move(move.lower())
  544.  
  545.  
  546.  
  547. class GGZNetworkDialog(ui.NetworkFeedback):
  548.     '''
  549.     '''
  550.     
  551.     def __init__(self, ui):
  552.         self.ui = ui
  553.         self.buffer = ''
  554.         self.profile = None
  555.         self.decoder = None
  556.  
  557.     
  558.     def addProfile(self, profile):
  559.         '''Called by ui.NetworkFeedback'''
  560.         (name, username, host, port) = profile
  561.         n = name
  562.         dupCount = 1
  563.         while True:
  564.             
  565.             try:
  566.                 self.ui.ggzConfig.getServer(n)
  567.             except KeyError:
  568.                 break
  569.                 continue
  570.  
  571.             dupCount += 1
  572.             n = '%s (%d)' % (name, dupCount)
  573.         name = n
  574.         self.ui.ggzConfig.updateServer(name, username, host, port)
  575.         return self.ui.ggzConfig.getServer(name)
  576.  
  577.     
  578.     def setProfile(self, profile):
  579.         '''Called by ui.NetworkFeedback'''
  580.         if profile is None:
  581.             name = '(none)'
  582.         else:
  583.             name = profile.name
  584.         print 'Profile=%s' % name
  585.         if self.decoder is not None:
  586.             self.decoder.close()
  587.         
  588.         self.decoder = None
  589.         self.controller.clearError()
  590.         self.controller.setSensitive(False)
  591.         self.controller.clearRooms()
  592.         self.controller.clearPlayers()
  593.         self.controller.clearTables()
  594.         self.controller.clearText()
  595.         self.profile = profile
  596.         if profile is None:
  597.             return None
  598.         self.decoder = GGZConnection(self)
  599.         self.decoder.client.start()
  600.  
  601.     
  602.     def enterRoom(self, room):
  603.         '''Called by ui.NetworkFeedback'''
  604.         print 'Entering room %s' % room.id
  605.         self.decoder._performAction(self.decoder.client.enterRoom, (room,))
  606.  
  607.     
  608.     def _addGame(self):
  609.         self.game = self.ui.application.addGame('Network Game')
  610.         if self.game is None:
  611.             return False
  612.         return True
  613.  
  614.     
  615.     def startTable(self):
  616.         '''Called by ui.NetworkFeedback'''
  617.         if self.decoder.room.game is None:
  618.             return None
  619.         if not self._addGame():
  620.             return None
  621.         print 'Starting table'
  622.         self.decoder.client.startTable(self.decoder.room.game.id, '', self.profile.login)
  623.  
  624.     
  625.     def joinTable(self, table):
  626.         '''Called by ui.NetworkFeedback'''
  627.         if not self._addGame():
  628.             return None
  629.         print 'Starting table %s' % table.id
  630.         self.decoder.client.joinTable(table)
  631.  
  632.     
  633.     def leaveTable(self):
  634.         '''Called by ui.NetworkFeedback'''
  635.         self.decoder.client.leaveTable()
  636.  
  637.     
  638.     def sendChat(self, text):
  639.         '''Called by ui.NetworkFeedback'''
  640.         self.decoder.client.sendChat(text)
  641.  
  642.  
  643.